package com.xilihui.xlh.business.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.dialogs.BuyDialog;
import com.xilihui.xlh.business.dialogs.MarqueDialog;
import com.xilihui.xlh.business.entities.BalanceEntity;
import com.xilihui.xlh.business.entities.CartListEntity;
import com.xilihui.xlh.business.entities.CheckEntity;
import com.xilihui.xlh.business.entities.GoodDetailsEntity;
import com.xilihui.xlh.business.requests.MyAppointmentRequest;
import com.xilihui.xlh.component.recyclerview.BaseAdapter;
import com.xilihui.xlh.component.recyclerview.BaseViewHolder;
import com.xilihui.xlh.component.recyclerview.LinearLayoutColorDivider;
import com.xilihui.xlh.constant.UrlConst;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.app.ToolBaseCompatActivity;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.feezu.liuli.timeselector.Utils.TextUtil;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/29.
 */

public class ChecklistActivity extends ToolBaseCompatActivity {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.cb_allSelect)
    CheckBox cb_all;
    @BindView(R.id.tv_totalNum)
    TextView tv_totalNum;
    @BindView(R.id.tv_jiesuan)
    TextView tv_jiesuan;

    BaseAdapter<CartListEntity.GoodsBean> baseAdapter;
    ArrayList<CartListEntity.GoodsBean> goodsBeans = new ArrayList<>();

    Intent intent;

    boolean isManage = true;
    boolean isCheckAll = true;


    int page = 1;
    String id = "";
    String wa_id = "";

    
    int qingdannum = 0;//清单数量
    float jiesuanJiner = 0;//结算金额
    int jiesuanNum = 0;//结算商品数量

    DecimalFormat decimalFormat=new DecimalFormat("0.00");


    @Override
    public int getLayout() {
        return R.layout.activity_checklist;
    }

    @Override
    public String initTitle() {
        return null;
    }

    @OnClick(R.id.iv_toolbar_left)
    public void back() {
        finish();
    }

    @OnClick(R.id.tv_toolbar_right)
    public void manage() {
        if (isManage) {
            setToolRightText("完成");
            tv_totalNum.setVisibility(View.INVISIBLE);
            tv_jiesuan.setText("删除");
            isManage = false;
        } else {
            setToolRightText("管理");
            tv_totalNum.setVisibility(View.VISIBLE);
            tv_jiesuan.setText("结算(3)");
            isManage = true;
            handle();
        }
    }

    @Override
    public void initUI(@Nullable final Bundle savedInstanceState) {

        setToolTitle("清单");
        setToolRightText("管理");
            
        recyclerView.addItemDecoration(new LinearLayoutColorDivider(getResources(), R.color.view_line, R.dimen.divider_space,
                LinearLayout.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        baseAdapter = new BaseAdapter<CartListEntity.GoodsBean>(this, goodsBeans) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_checklist;
            }

            @Override
            protected void getView(final BaseViewHolder holder, final CartListEntity.GoodsBean entity, final int position) {

                SimpleDraweeView simpleDraweeView = (SimpleDraweeView) holder.getView(R.id.iv_shop_img);
                simpleDraweeView.setImageURI(UrlConst.baseUrl() + entity.getOriginal_img());
                holder.setText(R.id.tv_shopName, entity.getGoods_name());
                String specName = entity.getSpec_key_name();
                if(TextUtil.isEmpty(specName)){
                    holder.setVisibility(R.id.tv_model,View.INVISIBLE);
                }else {
                    holder.setVisibility(R.id.tv_model,View.VISIBLE);
                    holder.setText(R.id.tv_model,specName);
                }
               
                holder.setText(R.id.tv_price, "￥" + entity.getGoods_price());
                holder.setText(R.id.tv_num, entity.getGoods_num() + "");


                CheckBox checkBox = (CheckBox) holder.getView(R.id.cb_select);

                if (entity.getSelected().equals("1")) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }

                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        String select = "";
                        if (b) {
                            select = "1";
                        } else {
                            select = "0";
                        }

                        final String finalSelect = select;
                        MyAppointmentRequest.checkGood(ChecklistActivity.this, id, entity.getId() + "", select)
                                .compose(DoTransform.<CheckEntity>applyScheduler(ChecklistActivity.this, false))
                                .subscribe(new HttpSubscriber<CheckEntity>(ChecklistActivity.this) {
                                    @Override
                                    protected void onSuccess(CheckEntity entity) {
                                        goodsBeans.get(position).setSelected(finalSelect);
                                        handle();
                                    }
                                        
                                    @Override
                                    protected void onFail(String msg) {
//                                                    ToastUtil.toastShortNegative(msg);
                                    }
                                });
                    }

                });

                holder.setOnClickListener(R.id.tv_model, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        final String good_id = entity.getGoods_id()+ "";
                        final String good_num = entity.getGoods_num()+"";
                        final String mid = entity.getId()+"";
                        MyAppointmentRequest.goodSpce(ChecklistActivity.this, entity.getId() + "", id + "")
                                .compose(DoTransform.<GoodDetailsEntity>applyScheduler(ChecklistActivity.this, true))
                                .subscribe(new HttpSubscriber<GoodDetailsEntity>(ChecklistActivity.this) {
                                    @Override
                                    protected void onSuccess(GoodDetailsEntity entity) {
                                        
                                        MarqueDialog marqueDialog = new MarqueDialog(ChecklistActivity.this,entity,mid,good_id, id,
                                                good_num,wa_id);
                                        marqueDialog.show();
                                        
                                    }

                                    @Override
                                    protected void onFail(String msg) {
                                        ToastUtil.toastShortNegative(msg);
                                    }
                                });
            
                    }
                });
                
                holder.setOnClickListener(R.id.iv_jian, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        int good_num = entity.getGoods_num();
                        if(good_num>1){
                            good_num = good_num -1;
                        }
                        final int finalGood_num = good_num;
                        MyAppointmentRequest.updateCart(ChecklistActivity.this,entity.getId()+"",id,"",good_num+"",wa_id)
                                .compose(DoTransform.<BaseEntity>applyScheduler(ChecklistActivity.this,true))
                                .compose(ChecklistActivity.this.<BaseEntity>bindToLifecycle())
                                .subscribe(new HttpSubscriber<BaseEntity>(ChecklistActivity.this) {
                                    @Override
                                    protected void onSuccess(BaseEntity ent) {
                                        entity.setGoods_num(finalGood_num);
                                        holder.setText(R.id.tv_num, finalGood_num+ "");
                                        handle();
                                    }

                                    @Override
                                    protected void onFail(String msg) {
                                        ToastUtil.toastShortNegative(msg);
                                    }
                                });

                    }
                });

                holder.setOnClickListener(R.id.iv_jia, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int good_num = entity.getGoods_num();
                        good_num = good_num + 1;
                        final int finalGood_num = good_num;
                        MyAppointmentRequest.updateCart(ChecklistActivity.this,entity.getId()+"",id,"",good_num+"",wa_id)
                                .compose(DoTransform.<BaseEntity>applyScheduler(ChecklistActivity.this,true))
                                .compose(ChecklistActivity.this.<BaseEntity>bindToLifecycle())
                                .subscribe(new HttpSubscriber<BaseEntity>(ChecklistActivity.this) {
                                    @Override
                                    protected void onSuccess(BaseEntity ent) {
                                        entity.setGoods_num(finalGood_num);
                                        holder.setText(R.id.tv_num, finalGood_num+ "");
                                        handle();
                                    }
                                    
                                    @Override
                                    protected void onFail(String msg) {
                                        ToastUtil.toastShortNegative(msg);
                                    }
                                });
                    }
                });

            }
        };

        baseAdapter.setAnimationsLocked(true);
        recyclerView.setAdapter(baseAdapter);


        cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                String select = "";
                if (b) {
                    select = "1";
                } else {
                    select = "0";
                }

                if(!isCheckAll){
                    isCheckAll = true;
                    return;
                }else {
                    isCheckAll = true;
                }
                
                final String finalSelect = select;
                MyAppointmentRequest.checkAll(ChecklistActivity.this, select, id)
                        .compose(DoTransform.<CheckEntity>applyScheduler(ChecklistActivity.this, true))
                        .subscribe(new HttpSubscriber<CheckEntity>(ChecklistActivity.this) {
                            @Override
                            protected void onSuccess(CheckEntity entity) {
                                int num = goodsBeans.size();
                                if (num > 0) {
                                    for (int i = 0; i < num; i++) {
                                        goodsBeans.get(i).setSelected(finalSelect);
                                    }
                                    baseAdapter.setList(goodsBeans);
                                    handle();
                                }
                            }

                            @Override
                            protected void onFail(String msg) {
                                ToastUtil.toastShortNegative(msg);
                            }
                        });

            }

        });

    }

    @Override
    public void initData() {
        id = getIntent().getStringExtra("id");
        wa_id = getIntent().getStringExtra("wa_id");
        getData();
    }


    @OnClick(R.id.tv_jiesuan)
    public void jiesuan() {
        
        if(jiesuanNum>0){
            if(isManage){
                MyAppointmentRequest.jiesuan(ChecklistActivity.this,id,wa_id)
                        .compose(DoTransform.<BalanceEntity>applyScheduler(this,true))
                        .compose(this.<BalanceEntity>bindToLifecycle())
                        .subscribe(new HttpSubscriber<BalanceEntity>(this) {
                            @Override
                            protected void onSuccess(BalanceEntity entity) {
                                intent = new Intent(ChecklistActivity.this,ConfirmListingActivity.class);
                                intent.putExtra("data",entity);
                                intent.putExtra("agent_id",id);
                                intent.putExtra("wa_id",wa_id);
                                startActivity(intent);
                            }

                            @Override
                            protected void onFail(String msg) {
                                ToastUtil.toastShortNegative(msg);
                            }
                        });
            }else {
                MyAppointmentRequest.deleteGoods(ChecklistActivity.this,id)
                        .compose(DoTransform.<BaseEntity>applyScheduler(this,true))
                        .compose(this.<BaseEntity>bindToLifecycle())
                        .subscribe(new HttpSubscriber<BaseEntity>(this) {
                            @Override
                            protected void onSuccess(BaseEntity entity) {
                                 getData();
                            }

                            @Override
                            protected void onFail(String msg) {
                                ToastUtil.toastShortNegative(msg);
                            }
                        });
            }
        }else {
            ToastUtil.toastShortNegative("请选择商品");
        }
        
        
    }

    public void getData() {

        MyAppointmentRequest.cartlist(this, id,wa_id)
                .compose(DoTransform.<CartListEntity>applyScheduler(this, true))
                .compose(this.<CartListEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<CartListEntity>(this) {
                    @Override
                    protected void onSuccess(CartListEntity entity) {
                        goodsBeans.clear();
                        goodsBeans.addAll(entity.getGoods());
                        boolean isall = true;
                        qingdannum = goodsBeans.size();
                        setToolTitle("清单(" + qingdannum + ")");
                        
                        if (goodsBeans.size() > 0) {
                            for (int i = 0; i < goodsBeans.size(); i++) {
                                if (goodsBeans.get(i).getSelected().equals("0")) {
                                    isall = false;
                                }
                            }
                            cb_all.setChecked(isall);
                        }
                        baseAdapter.setList(goodsBeans);
                        handle();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });

    }

    @Override
    public void onEventMainThread(YEventBuses.Event event) {
        super.onEventMainThread(event);
        if (event.is("cartupdate")) {
            getData();
        }else if (event.is("pay")){
            finish();
        }
    }

    public void handle() {
        boolean flag = true;
        float total = 0;
        jiesuanNum = 0;
        for (int i = 0; i < goodsBeans.size(); i++) {
            if (goodsBeans.get(i).getSelected().equals("0")) {
                flag = false;
            } else {
                jiesuanNum = jiesuanNum + 1;
                float price = Float.valueOf(goodsBeans.get(i).getGoods_price());
                int shuliang = goodsBeans.get(i).getGoods_num();
                total = total + price * shuliang;
                LogUtil.i("mylog","计算："+price+" "+shuliang+"="+total);
            }
        }
        
        if(cb_all.isChecked()&&!flag){
            isCheckAll = false;
        }else {
            isCheckAll = true;
        }
        
        cb_all.setChecked(flag);
        if(isManage){
            tv_jiesuan.setText("结算(" + jiesuanNum + ")");
            tv_totalNum.setText("合计：￥" + decimalFormat.format(total));
        }

    }


}
